package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alipay.api.domain.ReplyRecordResponse;
import com.alipay.api.response.AlipayMerchantTradecomplainQueryResponse;
import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.FileResponse;
import com.ytjj.common.utils.AliyunOSSClientUtil;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.qmyx.admin.mapper.ComplaintsRegistrationMapper;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.request.complaints.AliPayComplaintsImportRequest;
import com.ytjj.qmyx.admin.service.AliPayComplaintsService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.AlipayComplaintsRecordsMapper;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AliPayComplaintsServiceImpl  implements AliPayComplaintsService {
    @Resource
    private MallClient mallClient;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private AlipayComplaintsRecordsMapper alipayComplaintsRecordsMapper;

    @Resource
    private ComplaintsRegistrationMapper complaintsRegistrationMapper;

    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    @Override
    public List<ReplyRecordResponse> queryComplaintsHistory(String complainEventId) throws Exception{
        CommonResult<AlipayMerchantTradecomplainQueryResponse> commonResult = mallClient.queryAliPayComplaintsDetail(complainEventId, null);
        AlipayMerchantTradecomplainQueryResponse response = commonResult.getData();
        if (response !=null && !CollectionUtils.isEmpty(response.getReplyDetailInfos())) {
            return response.getReplyDetailInfos();
        }

        return null;
    }

    @Override
    public Map<String, String> getImgUrl(MultipartFile multipartFile, String complainEventId) {
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, multipartFile, "images");
        CommonResult<String> result = mallClient.uploadAliPayComplaintsImage(fileResponse.getUrl(),complainEventId);
        Map<String, String> map = new HashMap<>();
        map.put("url",fileResponse.getUrl());
        map.put("returnUrl",result.getData());
        return map;
    }

    @Override
    public CommonPage<AliPayComplaintsListResponse> aliPayComplaintsList(AliPayComplaintsListRequest request) {
        List<AliPayComplaintsListResponse> list = new ArrayList<>();
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        if(request.getComplainType() == 1){
            list = alipayComplaintsRecordsMapper.aliPayComplaintsList(request);
        }else if(request.getComplainType() == 2){
            list = alipayComplaintsRecordsMapper.aliPayTradeComplaintsListV2(request);
        }
        return CommonPage.restPage(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delTradeComplaints(List<Integer> ids) {
        StringBuffer error = new StringBuffer();
        for (Integer id : ids) {
            AlipayComplaintsRecords alipayComplaintsRecords = alipayComplaintsRecordsMapper.selectByPrimaryKey(id);
            if (alipayComplaintsRecords.getComplainType() != 2) {
                throw new ApiException(alipayComplaintsRecords.getComplainEventId() + "非交易投诉，无法删除。");
            }
            //删除主数据
            alipayComplaintsRecordsMapper.deleteByPrimaryKey(id);
            //删除子表数据
            complaintsRegistrationMapper.delByComplaintId(alipayComplaintsRecords.getComplainEventId());
        }
        return error.toString();
    }

    @Override
    public Integer markComplaintStatus(String complainEventId,String statusStr) {
        Admin admin = UserUtil.getAdmin();
        AlipayComplaintsRecords alipayComplaintsRecords = new AlipayComplaintsRecords();
        alipayComplaintsRecords.setComplainEventId(complainEventId);
        alipayComplaintsRecords.setComplainStatus(statusStr);
        alipayComplaintsRecords.setHandleTime(new Date());
        alipayComplaintsRecords.setHandlerUserId(admin.getId());
        return alipayComplaintsRecordsMapper.updateByParams(alipayComplaintsRecords);
    }

    @Override
    public AlipayComplaintsRecords queryByTradeNo(String tradeNo) {
        AlipayComplaintsRecordsExample example  =new AlipayComplaintsRecordsExample();
        example.createCriteria().andMerchantOrderNoEqualTo(tradeNo);
        List<AlipayComplaintsRecords> aliPayComplaintsRecords = alipayComplaintsRecordsMapper.selectByExample(example);
        return CollectionUtils.isEmpty(aliPayComplaintsRecords) ? null : aliPayComplaintsRecords.get(0);
    }

    @Override
    public String importComplaints(List<AliPayComplaintsImportRequest> requestList) {
        Map<String, String> result = new HashMap<>();
        int add = 0;
        int fail = 0;
        String msg = "";
        if (!CollectionUtils.isEmpty(requestList)) {
            //服务商导出的投诉特殊处理下
            if (!requestList.get(0).getMerchantOrderNo().startsWith("PAY")){
                for (AliPayComplaintsImportRequest aliPayComplaintsImportRequest:requestList){
                    if (aliPayComplaintsImportRequest.getMerchantOrderNo().contains("2010250")){
                        String[] merchantOrderNo = aliPayComplaintsImportRequest.getMerchantOrderNo().split(",");
                        int i=0;
                        String merchantNoNew = "";
                        for (String merchantNo : merchantOrderNo){
                            i++;
                            merchantNo = merchantNo.substring(merchantNo.indexOf("2010250"));
                            String resOrderNo = alipayComplaintsRecordsMapper.findResOrderNo(merchantNo);
                            if (i==1){
                                merchantNoNew = resOrderNo;
                            }else{
                                merchantNoNew +=","+resOrderNo;
                            }
                        }
                        aliPayComplaintsImportRequest.setMerchantOrderNo(merchantNoNew);
                    }
                }
            }



            //过滤去重
            Map<String, AliPayComplaintsImportRequest> map = requestList.stream().filter(item -> !StringUtils.isEmpty(item.getComplainEventId())).collect(Collectors.toMap(AliPayComplaintsImportRequest::getComplainEventId, item -> item, (v1, v2) -> v1));
            List<AliPayComplaintsImportRequest> complainEventIds = new ArrayList<>(map.values());
            if (!CollectionUtils.isEmpty(complainEventIds)) {
                //已存在的投诉单
                List<String> oldList = alipayComplaintsRecordsMapper.queryRecords(new ArrayList<>(map.keySet()));
                if (CollectionUtils.isEmpty(oldList)) {
                    add = saveOrUpdateAliPayComplaints(complainEventIds, true);
                } else {
                    List<AliPayComplaintsImportRequest> collect = complainEventIds.stream().filter(item -> oldList.contains(item.getComplainEventId())).collect(Collectors.toList());
                    fail = collect.size();
                    msg = "投诉单号：" + String.join(",", collect.stream().map(AliPayComplaintsImportRequest::getComplainEventId).collect(Collectors.toSet())) + "已存在，请勿重复导入";
                    if (collect.size() != complainEventIds.size()) {
                        //需要插入的数据
                        List<AliPayComplaintsImportRequest> collect2 = complainEventIds.stream().filter(item -> !oldList.contains(item.getComplainEventId())).collect(Collectors.toList());
                        add = saveOrUpdateAliPayComplaints(collect2, true);
                    }
                }
            }
        }
        if (fail > 0) {
            return String.format("新增：%s, 失败：%s, 失败原因：%s", add, fail, msg);
        } else {
            return String.format("新增：%s, 失败：%s", add, fail);
        }
    }

    /**
     * 保存或者更新导入数据
     * @param requestList
     * @param flag true 新增 false 更新
     * @return int
     */
    private int saveOrUpdateAliPayComplaints(List<AliPayComplaintsImportRequest> requestList, boolean flag) {
        int result = 0;
        List<AlipayComplaintsRecords> records = assembleComplaints(requestList);
        if (flag) {
            result = alipayComplaintsRecordsMapper.insertBatch(records);
        } else {
            for (AlipayComplaintsRecords record : records) {
                result += alipayComplaintsRecordsMapper.updateComplainByTradeNo(record);
            }
        }
        return result;
    }

    /**
     * 组装数据
     * @param requestList
     * @return List<AlipayComplaintsRecords>
     */
    private List<AlipayComplaintsRecords>  assembleComplaints(List<AliPayComplaintsImportRequest> requestList){
        Admin admin = UserUtil.getAdmin();
        List<String> tradeNoList = requestList.stream().filter(item -> !StringUtils.isEmpty(item.getMerchantOrderNo())).map(AliPayComplaintsImportRequest::getMerchantOrderNo).collect(Collectors.toList());
        List<ComplaintsOrderResponse> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tradeNoList)) {
            list = ordersInfoMapper.queryPlatformDataList(tradeNoList);
        }
        List<ComplaintsOrderResponse> finalList = list;
        List<AlipayComplaintsRecords> collect = requestList.stream().map(item -> {
            AlipayComplaintsRecords records = new AlipayComplaintsRecords();
            records.setImportUserId(admin.getId());
            records.setImportTime(new Date());
            records.setHandleTime(new Date());
            records.setHandlerUserId(admin.getId());
            records.setTargetId(item.getChildId());
            records.setTargetType("PID");
            records.setComplainEventId(item.getComplainEventId());
            records.setStatus("");
            records.setTradeNo(item.getTradeNo());
            records.setMerchantOrderNo(item.getMerchantOrderNo());
            records.setLeafCategoryName("");
            records.setComplainReason("");
            records.setContent(item.getContent());
            records.setImages("");
            records.setPhoneNo(item.getPhoneNo());
            records.setTradeAmount(StringUtils.isEmpty(item.getTradeAmount()) ? BigDecimal.ZERO : new BigDecimal(item.getTradeAmount()));
            records.setGmtCreate(StringUtils.isEmpty(item.getGmtCreate()) ? new Date() : DateTimeUtil.StrToTime(item.getGmtCreate()));
            records.setGmtModified(new Date());
            records.setGmtFinished(null);
            records.setChildId(item.getChildId());
            records.setComplainType(2);
            records.setComplainDealType(item.getComplainDealType());
            records.setDealRemark(item.getDealRemark());
            records.setComplainStatus(item.getComplainStatus());
            List<ComplaintsOrderResponse> collect1 = finalList.stream().filter(item2 -> item2.getTradeNo().equals(item.getMerchantOrderNo())).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(collect1)) {
                records.setSupplyProductId(collect1.get(0).getSupplyProductId());
                String domain_url = org.apache.commons.lang3.StringUtils.isNotBlank(collect1.get(0).getDomainUrl()) ? "_非支付宝" : "_支付宝渠道";
                records.setPlatformData(collect1.get(0).getOrderSource() + domain_url);
            }
            return records;
        }).collect(Collectors.toList());
        return collect;
    }
}
